package com.gpj.mini.tools.fr;

import java.io.*;

/**
 * @className FindAndReplace
 * @description
 *   TODO
 * @author GPJ
 * @date 2021/6/17 16:57
 * @version 1.0
 **/
public class FindAndReplace {
	private static final String BAK_SUFFIX = ".bak";

	/**
	 * 替换指定文件中的字符串
	 * @param filePath 文件路劲
	 * @param source 目标字符串
	 * @param target 要替换成的字符串
	 */
	public static boolean findReplace(String filePath, String source, String target) {
		if(!doFindReplace(filePath, source, target)) return false;

		File file = new File(filePath);
		File fileBak = new File(filePath + BAK_SUFFIX);

		if (!file.exists() || !fileBak.exists()) return false;

		file.delete();
		fileBak.renameTo(file);
		return true;
	}

	public static boolean doFindReplace(String filePath, String source, String target) {
		File file = new File(filePath);
		if (!file.exists()) {
			return false;
		}

		try (
			FileInputStream in = new FileInputStream(filePath);
			PrintWriter out = new PrintWriter(filePath + BAK_SUFFIX);
		) {
			Long length = file.length();
			byte[] context = new byte[length.intValue()];

			in.read(context);
			String fileContext = new String(context);
			fileContext = fileContext.replace(source, target);

			out.write(fileContext.toCharArray());
			out.flush();
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}
}
